<template>
  <div>
    <Dialog
      v-model="showDialog"
      :title="`门票策略`"
      :width="`${dialogWidth}px`"
      :before-close="cancel"
      @open="openDialog"
    >
      <el-form
        v-loading="loading"
        ref="ruleFormRef"
        :model="formData"
        :rules="rules"
        label-width="95px"
        class="demo-ruleForm"
      >
        <!-- 第一步 -->
        <div v-show="step == 1">
          <el-form-item label="选择区域" prop="pageFlags">
            <el-select v-model="formData.pageFlags" placeholder="请选择区域">
              <el-option
                multiple
                v-for="item in pageAreaTypes"
                :key="item.pageFlag"
                :label="item.name"
                :value="item.pageFlag"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发放数量" prop="请选择区域">
            <el-input-number v-model="formData.ticketNum" :min="1" :max="9999" />
          </el-form-item>
          <el-form-item label="生效日期" prop="startTime">
            <el-date-picker
              v-model="time"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="defaultTime"
            />
          </el-form-item>
        </div>

        <!-- 第二步 -->
        <div v-show="step == 2">
          <el-form-item label="发放范围" prop="storeName">
            <el-radio-group v-model="formData.type">
              <el-radio-button :label="2">{{ "配置规则引擎" }}</el-radio-button>
              <el-radio-button :label="1">{{ "自定义人群范围" }}</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <div v-show="formData.type == 2">
            <Limits
              v-model="limitsList"
              :options="setLimitCompontentList()"
              :disabled="readOnly"
            ></Limits>
          </div>
          <div v-show="formData.type == 1" class="content-box">
            <div class="left">
              <SearchBar inline>
                <template #normal>
                  <el-form-item label="唯一标识">
                    <el-input
                      v-model="tableForm.unionId"
                      clearable
                      placeholder="请输入唯一标识"
                    ></el-input>
                  </el-form-item>
                </template>
              </SearchBar>
              <LayoutTable
                ref="tableRef"
                url="/user/userEntity/pageList"
                :rowKey="
                  (row: any) => {
                    return String(row.id);
                  }
                "
                :param="tableForm"
                @selection-change="selectionChange"
              >
                <el-table-column type="selection" :reserve-selection="true" width="55" />
                <el-table-column prop="unionId" label="唯一标识" min-width="100">
                </el-table-column>
                <el-table-column prop="phone" label="手机号" min-width="120">
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  label="注册时间"
                  min-width="170"
                >
                  <template #default="scope">
                    <div>
                      {{dateFormat(scope.row.createTime)}}
                    </div>
                  </template>
                </el-table-column>
              </LayoutTable>
            </div>
            <div class="right">
              <span>已选中{{ selectionList.length }}条</span>
              <div
                class="_item"
                v-for="(item, idx) in selectionList"
                :key="idx"
                @click="delItem(item)"
              >
                {{ item.unionId }}

                <el-icon class="icon-close"><Close /></el-icon>
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button v-show="step == 2" type="primary" @click="setStep(1)"
            >上一步</el-button
          >
          <el-button v-show="step == 1" type="primary" @click="validateForm"
            >下一步</el-button
          >
          <el-button v-show="step == 2" type="primary" @click="submit" :loading="loading"
            >确定</el-button
          >
        </span>
      </template>
    </Dialog>
  </div>
</template>
<script lang="ts" setup>
import Limits from "@/components/limits/Index.vue";
import { distributeTicket } from "@/api/activity";
import { dateFormat } from "@/utils/filters";
import { setLimitCompontentList } from "@/utils/index";
const props = defineProps({
  showDialog: Boolean,
  pageAreaTypes: {
    type: Object,
    default: {},
  },
});
const Route = useRoute();
const { pageAreaTypes, showDialog } = toRefs(props);
const loading = ref(false);
const dialogWidth = ref(500);
const tableRef = ref();
const ruleFormRef = ref();
const step = ref(1);
const time = ref("" as any);
const limitsList = ref({});
const readOnly = ref(false);
const selectionList = ref([]);
const tableForm = ref({
  unionId: "",
})
const formData = ref({
  actId: "",
  type: 2,
  pageFlags: "",
  ticketNum: 1,
  startTime: "",
  endTime: "",
  matchData: "",
});
const defaultTime: [Date, Date] = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
];
watch(time, (val) => {
  console.log("[ val ]", val);
  if (val) {
    formData.value.startTime = String(new Date(val[0]).getTime());
    formData.value.endTime = String(new Date(val[1]).getTime());
    console.log("[ formData.value.startTime ]", formData.value.startTime);
  } else {
    formData.value.startTime = "";
    formData.value.endTime = "";
  }
});
const rules = ref({
  pageFlags: [{ required: true, message: "请选择配置", trigger: "blur" }],
  startTime: [{ required: true, message: "请选择生效日期", trigger: "blur" }],
});
const openDialog = () => {
  // time.value = [1672934400000, 1672939400000];
  formData.value.actId = String(Route.params.id);
};

const validateForm = async () => {
  ruleFormRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      setStep(2);
    }
  });
};
const setStep = (type: number) => {
  step.value = type;
  if (type == 2) {
    dialogWidth.value = 1200;
  } else {
    dialogWidth.value = 500;
  }
};
const selectionChange = (val: any, row: any) => {
  console.log("[ val ]", val);
  selectionList.value = val;
};
const delItem = (item: any) => {
  console.log("[ tableRef.value  ]", tableRef.value.$refs.elTable);
  tableRef.value.$refs.elTable.toggleRowSelection(item, false); // 单条清空
  // tableRef.value.$refs.elTable.clearSelection() // 全部清空
};
const submit = async () => {
  if (formData.value.type == 2) {
    if (JSON.stringify(limitsList.value) !== "{}") {
      formData.value.matchData = JSON.stringify(limitsList.value);
    } else {
      ElMessage.warning("请配置规则引擎");
      return;
    }
  } else {
    if (selectionList.value.length) {
      formData.value.matchData = String(selectionList.value.map(item=>item.id))
    } else {
      ElMessage.warning("请选择发放人群");
      return;
    }
  }
  let rs = await distributeTicket(formData.value);
  if (rs.code === 200) {
    ElMessage.success("保存成功");
    confirm();
  }
};
const confirm = () => {
  emit("confirm");
  cancel();
};

const cancel = () => {
  emit("cancel");
  setTimeout(() => {
    formData.value = {
      actId: "",
      type: 2,
      pageFlags: "",
      ticketNum: 1,
      startTime: "",
      endTime: "",
      matchData: "",
    };
    step.value = 1;
    dialogWidth.value = 500;
    limitsList.value = {};
    tableRef.value.$refs.elTable.clearSelection();
    time.value = "";
    ruleFormRef.value.resetFields();
  }, 500);
};

const emit = defineEmits(["confirm", "cancel"]);
</script>

<style lang="scss" scoped>
.content-box {
  display: flex;
  .left {
    width: 750px;
  }
  .right {
    flex: 1;
    width: 500px;
    margin-left: 20px;
    ._item {
      display: flex;
      align-items: center;
      position: relative;
      line-height: 26px;
      margin: 3px 0;
      .el-icon {
        position: absolute;
        right: 10px;
        display: none;
      }
      :deep(.icon-close:before) {
        content: "";
      }
      &:hover {
        background: #ddd;
        cursor: pointer;
        .el-icon {
          display: block;
        }
      }
    }
  }
}
</style>
